package com.caszx.chargingpile.fragment.reservate;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSONException;
import com.app.base.adapter.BaseClickRecyclerAdapter;
import com.app.base.adapter.BaseHeadFootAdapter;
import com.app.base.fragment.BaseNetViewFragment;
import com.app.jsonparse.JSONParse;
import com.app.utils.DiskUser;
import com.baidu.location.BDLocation;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.activity.ReservatePayActivity;
import com.caszx.chargingpile.activity.UserSignInActivity;
import com.caszx.chargingpile.entity.EntityCommPile;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.eventbus.OfenReservateStation;
import com.caszx.chargingpile.holder.reservate.OftenUseHolder;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.user.LocationManager;
import com.caszx.chargingpile.utils.DialogHelp;
import com.caszx.chargingpile.utils.SnackbarHelp;
import com.rey.material.app.DialogFragment;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.Call;

/**
 *
 * 预约->常用电站
 */
public class OftenUsedFragment extends BaseNetViewFragment {

    private RecyclerView mRecyclerView;
    private BaseHeadFootAdapter<EntityCommPile> mRecyclerAdapter;
    private PtrClassicFrameLayout ptrFrame;

    public static OftenUsedFragment newInstance() {
        OftenUsedFragment fragment = new OftenUsedFragment();
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }
    /**
     * 定位的回调
     * */
    public void onEvent(String action){
        if(EventBusAction.ACTION_REQUEST_LOCATION_SU.equals(action)){
            //定位成功
            String city = LocationManager.getInstance().getCityName();
            if(!TextUtils.isEmpty(city)) {
                onLoad();
            }
        }else  if(EventBusAction.ACTION_REQUEST_LOCATION_ER.equals(action)){
            //定位失败
            showErrorView("定位失败");
        }else  if(EventBusAction.ACTION_SING_OUT.equals(action)){
            //用户退出
            if(mRecyclerAdapter!=null){
                mRecyclerAdapter.clear();
            }
        }else  if(EventBusAction.ACTION_SING_IN.equals(action)){
            //用户登录
            String city = LocationManager.getInstance().getCityName();
            if(!TextUtils.isEmpty(city)) {
                onLoad();
            }
        } else if(EventBusAction.ACTION_CHANGE_ADD_COMM_SATION.equals(action)){
            String city = LocationManager.getInstance().getCityName();
            if(!TextUtils.isEmpty(city)) {
                onLoad();
            }
        }
    }

    /**
     * 预约和删除的回调
     * */
    public void onEvent(final OfenReservateStation action){
        if(action.isDelete){
            DialogHelp.showDialogOnlyMesg(getContext(), "是否删除?", new DialogHelp.DialogActionClickListener() {
                @Override
                public void onPositiveActionClicked(DialogFragment fragment) {
                    deleteCommStation(action.id,action.position);
                }
                @Override
                public void onNegativeActionClicked(DialogFragment fragment) {
                }
            });

        }else{
            Intent intent = new Intent(getActivity(),ReservatePayActivity.class);
            intent.putExtra("ID",action.id);
            intent.putExtra("NAME",action.name);
            getActivity().startActivity(intent);
        }
    }

    @Override
    protected void onLoad() {
        String city = LocationManager.getInstance().getCityName();
        if(TextUtils.isEmpty(city)) {
            EventBus.getDefault().post(EventBusAction.ACTION_REQUEST_LOCATION);
            return;
        }

        HashMap<String,String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(getActivity(),"token"));
        params.put("latitude",LocationManager.getInstance().getLatitude()+"");
        params.put("longitude",LocationManager.getInstance().getLongitude()+"");
        OkHttpUtils.post()
                .url(ConstantUrl.URL_COMM_STATION)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        if(ptrFrame!=null){
                            ptrFrame.refreshComplete();
                        }
                        showErrorView(R.string.error_network);
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        if(ptrFrame!=null){
                            ptrFrame.refreshComplete();
                        }
                        JSONObject resultJsonObject =  response.optJSONObject("result");
                        if(resultJsonObject!=null){

                            int code =  resultJsonObject.optInt("code");
                            if(code==-100){
                                DialogHelp.showDialogOnlyMesg(getActivity(),getResources().getString(R.string.error_minus_100), new DialogHelp.DialogActionClickListener() {
                                    @Override
                                    public void onPositiveActionClicked(DialogFragment fragment) {
                                        Intent intent = new Intent(getActivity(),UserSignInActivity.class);
                                        startActivity(intent);
                                        showErrorView(getResources().getString(R.string.error_minus_100));
                                    }

                                    @Override
                                    public void onNegativeActionClicked(DialogFragment fragment) {
                                    }
                                });
                                showErrorView(getResources().getString(R.string.error_minus_100));
                                return;
                            }

                            if(code<0){
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"),null);
                                showErrorView(resultJsonObject.optString("msg"));
                            }else{
                                try {
                                    List<EntityCommPile> datas = JSONParse.parseArray(response.optString("commomPileList"),EntityCommPile.class);
                                    showContentView();
                                    mRecyclerAdapter.setDatas(datas);
                                }catch (JSONException e){
                                    showErrorView(R.string.error_parser_json);
                                }
                            }
                        }
                    }
                });
    }

    @Override
    protected View initOnloadedView() {
        View view = getActivity().getLayoutInflater().inflate(
                R.layout.common_refrash_recyclerview, null);
        initPtrFrameLayout(view);
        initRecyclerView(view);
        return  view;
    }

    private void initPtrFrameLayout(View view) {
        ptrFrame = (PtrClassicFrameLayout) view
                .findViewById(R.id.ptr_classic_frameLayout);
        ptrFrame.setLastUpdateTimeRelateObject(this);
        ptrFrame.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                onLoad();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame,
                                             View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(ptrFrame,
                        mRecyclerView, header);
            }
        });
    }
    private void initRecyclerView(View view) {

        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mRecyclerView.setBackgroundResource(R.color.gray3);
        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        LinearLayoutManager layoutManager = new LinearLayoutManager( getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setHasFixedSize(true);

        //mRecyclerView.setItemAnimator(new SlideInOutBottomItemAnimator(mRecyclerView));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerAdapter = new BaseHeadFootAdapter<>(R.layout.item_reservate_often_use,OftenUseHolder.class);
        mRecyclerView.setAdapter(mRecyclerAdapter);

    }


    private void deleteCommStation(String id, final int position){
        showProgressDialog("删除中...");
        HashMap<String, String> params = new HashMap<>();
        String token =  DiskUser.getStringValueByKey(getActivity(),"token");
        params.put("stationId", id);
        params.put("token", token);
        OkHttpUtils.post()
                .url(ConstantUrl.URL_USER_CANCEL_STATION_)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                       SnackbarHelp. showSnackbarMsg(getActivity(),getResources().getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                SnackbarHelp.  showSnackbarMsg(getActivity(),resultJsonObject.optString("msg"));
                            } else {
                                mRecyclerAdapter.removeItem(position);
                            }
                        }
                    }
                });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
